﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Business
{
    public class BVVDDataStore<T>
    {
        BVVDDataContext db = new BVVDDataContext();
        public List<T> getFromDB(Hashtable condition)
        {
            var metadata = (from meta in (db.Mapping.MappingSource
                       .GetModel(typeof(BVVDDataContext))
                       .GetMetaType(typeof(T))
                       .DataMembers)
                            select meta).ToList();
            string query = "SELECT ";
            foreach (MetaDataMember col in metadata)
            {

                if (metadata.IndexOf(col) < metadata.Count - 1)
                {
                    if (!String.IsNullOrEmpty(col.DbType))
                    {
                        query += col.Member.Name + ",";
                    }
                }
                else
                {
                    query = query.Substring(0, query.Length - 1) + " FROM " + Activator.CreateInstance<T>().GetType().Name;

                }


            }
            if (condition.Count > 0)
            {
                int step = 0;
                query += " WHERE ";
                foreach (DictionaryEntry filter in condition)
                {
                    query += filter.Key + "='" + filter.Value + "'";
                    if (++step < condition.Count)
                    {
                        query += " AND ";
                    }
                }

            }

            List<T> list = db.ExecuteQuery<T>(query).ToList();
            return list;

        }

        


    }
}
